package com.course.rocketmq.consumer;

import com.alibaba.fastjson.JSON;
import com.course.model.entity.redisson.UserOrder;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * @PROJECT_NAME: course
 * @DESCRIPTION: 消费消息监听类
 * @Author: 涂玄武
 * @DATE: 2021/6/8 15:21
 */
@Component
@RocketMQMessageListener(topic = "my-topic",consumerGroup = "demo-consumer-group")
public class ConsumerSimple implements RocketMQListener<String> {

    private static final Logger logger = LoggerFactory.getLogger(ConsumerSimple.class);

    /**
     * 消费消息
     * @param msg
     */
    @Override
    public void onMessage(String msg) {
        //此方法被调用表示接收到消息，msg形参就是消息内容
        //处理消息
        logger.info("接受消息:{}",msg);
        //如果是json数据，可以将json转为对象
//        UserOrder userOrder = JSON.parseObject(msg, UserOrder.class);
//        logger.info("接受Json格式消息：{}",userOrder.toString());
    }

    /**
     * 消费重试
     * @param messageExt
     */
    public void onMessage(MessageExt messageExt) {
        //取出当前重试次数
        int reconsumeTimes = messageExt.getReconsumeTimes();
        //当大于一定的次数后将消息写入数据库，由单独的程序或人工去处理
        if (reconsumeTimes >= 2){
            //将消息写入数据库，之后正常返回
            return;
        }
        throw new RuntimeException(String.format("第%s次处理失败...",reconsumeTimes));
    }


}
